package com.gw.task;


import com.gw.mapper.EssayMapper;
import com.gw.pojo.entity.HotEssay;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class EssayTask {

    @Autowired
     private EssayMapper essayMapper;


    /**
     * 每天获取csdn热榜十篇文章
     */
    @Scheduled(cron = "0 0 8 * * ?")  //每天早上八点
    public void getHotEssay(){
        //在获取之前先清除前一天的数据库热榜信息
        essayMapper.delete();

        log.info("获取csdn每日热榜");
        try {
            Document doc = Jsoup.connect("https://csdn.net").get();
            //获取class属性为 headswiper-item 的片段
            Elements elementsByClass = doc.getElementsByClass("headswiper-item");
            //获取标签为 a 的部分
            Elements links = elementsByClass.select("a");

            List<HotEssay> list = new ArrayList<>();
            int i = 0;
            for (Element link : links){
                i++;
                if (i % 2 != 0){
                    HotEssay hotEssay = HotEssay.builder()
                            .title(link.text())
                            .url(link.attr("href"))
                            .build();
                    list.add(hotEssay);
                }
            }
            essayMapper.addEssay(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
